// hooks/useUser.ts
import { useState, useEffect } from 'react';
import Taro from '@tarojs/taro';
import { request } from '@/utils/request';
import { WxLogin } from '@/utils/wxLogin';

export interface UserInfo {
  id: number;
  nickname?: string;
  avatar?: string;
  mobile?: number;
  sex?: number;
  point?: number;
  experience?: number;
  level?: {
    id: number;
    name?: string;
    level?: number;
    icon?: string;
  };
  realNameAuth?: boolean;
  name?: string;
  idCard?: number;
  appraiserLevel?: number;
  brokerageEnabled?: boolean;
  subscriptionExpireTime?: string;
  subscriptionPackageId?: number;
}

export const useUser = () => {
  const [user, setUser] = useState<UserInfo | null>(null);
  const [loading, setLoading] = useState(true);

  const fetchUser = async () => {
    setLoading(true);
    try {
      const res = await request.get('/member/user/get', {}, true);
      setUser(res);
    } catch (err) {
      setUser(null);
    } finally {
      setLoading(false);
    }
  };

  const logout = async () => {
    await WxLogin.logout(false); // 不跳转页面
    setUser(null); // 清空页面状态
  };

  useEffect(() => {
    fetchUser();
  }, []);

  return { user, loading, fetchUser, logout };
};
